package com.dreamer.service.sign.impl;

import com.dreamer.domain.sign.SignCount;
import com.dreamer.domain.user.AccountsTransfer;
import com.dreamer.domain.user.User;
import com.dreamer.domain.user.enums.AccountsType;
import com.dreamer.repository.sign.SignCountDao;
import com.dreamer.repository.user.MutedUserDAO;
import com.dreamer.service.mobile.AccountsHandler;
import com.dreamer.service.mobile.AccountsTransferHandler;
import com.dreamer.service.mobile.impl.BaseHandlerImpl;
import com.dreamer.service.sign.SignCountHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ps.mx.otter.exception.ApplicationException;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;


@Service
public class SignCountHandlerimpl extends BaseHandlerImpl<SignCount> implements SignCountHandler {

    private SignCountDao signCountDao;

    @Autowired
    private AccountsTransferHandler accountsTransferHandler;

    @Autowired
    private MutedUserDAO mutedUserDAO;

    @Autowired
    public void setSignCountDao(SignCountDao signCountDao) {
        this.signCountDao = signCountDao;
        this.setBaseDao(signCountDao);
    }


    @Override
    @Transactional
    public void sign(User user) {
        SignCount signCount = signCountDao.get("userId", user.getId());
        if (signCount == null) {
            signCount = new SignCount(user.getId(), new Date(), 1, 1);
            signCountDao.merge(signCount);
            //送积分
            accountsTransferHandler.transferAccounts(mutedUserDAO.loadFirstOne().getId(), user.getId(), AccountsType.POINT.getState(), new Double(10), "每天签到奖励!");
        } else {
            LocalDate date = signCount.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate now = LocalDate.now();
            if (date.isEqual(now)) {
                throw new ApplicationException("对不起您今天已经签过到了!");
            }
            signCount.setDate(new Date());//更新签到时间
            signCount.setAllCount(signCount.getAllCount() + 1);//更新累计签到数
            if(now.minusDays(1).equals(date)){ //如果最近签到是昨天
                signCount.setCount(signCount.getCount()+1);//连续签到+1
            }else {//重置连续签到数
                signCount.setCount(1);
            }
            signCountDao.merge(signCount);
            accountsTransferHandler.transferAccounts(mutedUserDAO.loadFirstOne().getId(), user.getId(), AccountsType.POINT.getState(), new Double(10), "每天签到奖励!");
        }

    }
}
